package com.lanlian.cayman.activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.bean.CMinute;
import com.example.bean.FenshiDataResponse;
import com.example.bean.MyStatic;
import com.example.bean.StickData;
import com.example.myview.MsgView;
import com.example.utils.LineUtil;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.bean.EventZixuanData;
import com.lanlian.cayman.bean.GearBean;
import com.lanlian.cayman.bean.Market;
import com.lanlian.cayman.bean.MyContractBean;
import com.lanlian.cayman.dialog.GoodsSelectDialog;
import com.lanlian.cayman.dialog.PlaceOrderDialogManager;
import com.lanlian.cayman.fragment.GearFragment;
import com.lanlian.cayman.fragment.GoodsFragment;
import com.lanlian.cayman.fragment.MarketFragment;
import com.lanlian.cayman.kline.utils.MyDataParse;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.CLOrientationDetector;
import com.lanlian.cayman.utils.KlneUtil;
import com.lanlian.cayman.utils.MResUtil;
import com.lanlian.cayman.utils.NumberManager;
import com.lanlian.cayman.utils.TimeUtil;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.cayman.view.RiskInvestigationDialog;
import com.lanlian.cayman.widget.TopView;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.PositionDetailsInfo;
import com.lanlian.commonlib.bean.ReqGetTradeTime;
import com.lanlian.commonlib.bean.db.DBMarketS;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.data.ContractBean;
import com.lanlian.commonlib.data.GoodsBean;
import com.lanlian.commonlib.data.MarketBean;
import com.lanlian.commonlib.data.RespMarket;
import com.lanlian.commonlib.data.RespTradeTime;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.uikit.CustomDialog;
import com.oms.rpc.protobuf.KLineHqResp;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.TickHqReq;
import com.oms.rpc.protobuf.TickHqResp;
import com.oms.rpc.protobuf.YsHqInfo;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 大盘
 */


public class KLineActivity extends KLineActivityBase
{
   static CLOrientationDetector cd;
    //横屏
    ImageView iv_search;
    ImageView iv_close;
    TextView tv_xiadan;
    TextView tv_add;


   //竖屏
    TextView iv_chicang;
    TextView iv_zhixuan;
    TextView iv_hangqing;





    Activity act=this;
    RespTradeTime mRespTradeTime;

    ArrayList<GearBean> buy;

    private MagicIndicator mMagicIndicator;
    private ViewPager mViewPager;

    private String[] mTitleList = new String[]{"成交行情", "合约细则"};
    private static ArrayList<View> mFragments = new ArrayList<>();
    TextView tv_buy;
    TextView tv_sell;
    TextView tv_cangchi;
    TextView tv_price;
    TextView tv_change;
    TextView tv_chg;

    HqMsg.YsHqInfo yhc;


    LinearLayout ll_left;
    Handler handler1_gear;
    private ArrayList<StickData> list;
    LinearLayout ll_name;
    LinearLayout ll_select;
    /**
     * 顶部指示箭头
     */
    ImageView iv_zhishi;
    TextView tv_zhixuan;

    FenshiDataResponse fd;
    /**
     * 交易时间
     */

    String time=null;

    PositionDetailsInfo pi;
    PlaceOrderDialogManager pm;
    String scale="0.01";
    int count;
    /**
     * 当前选项
     */
    int cindex=0;

    CLOrientationDetector cl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // instance = ScreenSwitchUtils.init(this.getApplicationContext());
        klineType=0;
        selectType=0;
        zhibiaoTop=0;
        zhibiao=0;
        MyStatic.reSet();
        cl=new CLOrientationDetector(this);
        cl.setIcb(new CLOrientationDetector.Icb() {
            @Override
            public void back(boolean isPoart) {

               if(isPoart)
               {
                   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
               }
               else
               {
                   Intent intent=new Intent(act, KLineHengPingActivity.class);
                   intent.putExtra("id",id);
                   intent.putExtra("name",name);
                   intent.putExtra("index",klineType);
                   intent.putExtra("selectType",selectType);

                   act.startActivity(intent);
               }
            }
        });



        name=getIntent().getStringExtra("name");
        id=getIntent().getStringExtra("id");
        pi=(PositionDetailsInfo)getIntent().getSerializableExtra("pi");
        setContentView(R.layout.activity_kline2);
        mDBManager = DBManager.getInstance();
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE)
        {


        } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {


        }

        reData();

        if(pi!=null)
        {
            qingcang();
        }
       // kline.setType(klineType,zhibiaoTop);

        if(1==1)
        {
            long a=1543507200%(24*60*60);
            int b=1;
        }
    }

    @Override
    protected void setRequestedOrientation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    private void switchData()
    {
        try {

            scale= MarketFragment.getRespMarket().getGoods(id).minChange;


            getTradeTime();

            if(selectType==0)
            {
                initDataWuDang();
                initFenShiData();
            }
            else
            {
                initKlneData(selectType);
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    private void reData()
    {


            initView();


           GoodsBean gb=MarketFragment.getRespMarket().getGoods(id);
           if(gb!=null)
           {
               scale= gb.minChange;
           }

            initDataWuDang();

            getTradeTime();

            if(selectType==0)
            {
                initFenShiData();

            }
            else
            {
                initKlneData(selectType);
            }
            count=NumberManager.getNumberDecimalDigits(scale);
            kline.setScalePrice(count);
            kline.setType(klineType,zhibiaoTop);

    }
    private void initDataWuDang()
    {
        ProtoManager pm2=new ProtoManager();
        try {
            TickHqReq.Builder builder = pm2.getTickHqReq();
            builder.setStrcontractno(id);
            //下面的方法必须最后调用
            OMSTradeReq.Builder oms=pm2.getRequst(6);
            OMSTradeReq om=oms.build();
            SocketCallImpl sc=new SocketCallImpl(this){
                @Override
                public void message(byte[] data) {
                   try
                   {
                       OMSTradeRsp oms=  OMSTradeRsp.parseFrom(data);
                       TickHqResp hr= oms.getTickhqResp();
                       YsHqInfo yh=hr.getTickhqinfo(0);

                       count=NumberManager.getNumberDecimalDigits(scale);

                       MyContractBean mb=MyContractBean.switchData(yh,count);
                      setData(mb);
                      if(pm!=null&&tv_price.getText()!=null)
                      {
                          pm.setPrice(tv_price.getText().toString());

                      }


                       buy = new ArrayList<>();
                       ArrayList<GearBean> sell = new ArrayList<>();


                       GearBean gb = null;
                       for (int i = 0; i < yh.getQBidPriceCount(); i++) {
                           gb = new GearBean();
                           gb.id = 1 + i + "";
                           gb.price = NumberManager.getString4or5(yh.getQBidPrice(i) + "", "1", count);
                           gb.num = yh.getQBidQty(i) + "";

                           buy.add(gb);
                       }
                       for (int i = 0; i < yh.getQAskPriceCount(); i++) {
                           gb = new GearBean();
                           gb.id = 1 + i + "";

                           gb.price = NumberManager.getString4or5(yh.getQAskPrice(i) + "", "1", count);
                           gb.num = yh.getQAskQty(i) + "";
                           sell.add(gb);
                       }

                       kline.setLastPrice(mb.ClosingPrice);
                       kline.setGearData(buy, sell);

                   }
                   catch (Exception e)
                   {
                       e.printStackTrace();
                   }
                }
            };
            MySocketManager ms=new MySocketManager();
            ms.setCongLian(true);
            ms.sendData(om.toByteArray(),sc);
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
   private void initDataGoods()
   {
       GoodsFragment gf=(GoodsFragment) mFragments.get(1);

       gf.setData(id,act);
   }

    private void initFragments() {
        mFragments.clear();
        for (int i=0;i<mTitleList.length;i++) {
            if(i==0)
            {
                mFragments.add(new GearFragment(act));
            }
           else if(i==1)
            {
                mFragments.add(new GoodsFragment(act));
            }
        }
    }
    private void initViewPort()
    {
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
//            iv_search=findViewById(R.id.iv_search);
//            iv_search.setOnClickListener(this);
//            iv_close=findViewById(R.id.iv_close);
//            iv_close.setOnClickListener(this);
//
//            tv_xiadan=findViewById(R.id.tv_xiadan);
//            tv_xiadan.setOnClickListener(this);
//            tv_add=findViewById(R.id.tv_add);
//            tv_add.setOnClickListener(this);
//            if(DBMarketS.isHas(id))
//            {
//                tv_add.setText("删自选");
//            }else
//            {
//                tv_add.setText("加自选");
//            }

        } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {

            tv_buy=findViewById(R.id.tv_buy);
            tv_buy.setOnClickListener(this);
            tv_sell=findViewById(R.id.tv_sell);
            tv_sell.setOnClickListener(this);
            mMagicIndicator = findViewById(R.id.magic_indicator);
            mViewPager = findViewById(R.id.view_pager);
            mViewPager.setCurrentItem(1);
            tv_zhixuan=findViewById(R.id.tv_zhixuan);
            tv_zhixuan.setOnClickListener(this);
            if(DBMarketS.isHas(id))
            {
                tv_zhixuan.setText("删自选");
            }else
            {
                tv_zhixuan.setText("加自选");
            }
            ll_left=(LinearLayout) findViewById(R.id.ll_left);
            ll_left.setOnClickListener(this);
            iv_zhishi=findViewById(R.id.iv_zhishi);
            ll_select=findViewById(R.id.ll_select);
            ll_name=findViewById(R.id.ll_name);
            ll_name.setOnClickListener(this);
            initFragments();
            initNavigator();
            initDataGoods();
        }

    }
    @Override
    protected void initView() {
        iv_chicang=findViewById(R.id.iv_chicang);
        iv_zhixuan=findViewById(R.id.iv_zhixuan);
        iv_hangqing=findViewById(R.id.iv_hangqing);
        iv_chicang.setOnClickListener(this);
        iv_zhixuan.setOnClickListener(this);
        iv_hangqing.setOnClickListener(this);
        tv_price=findViewById(R.id.tv_price);
        tv_change=findViewById(R.id.tv_change);
        tv_chg=findViewById(R.id.tv_chg);

        tv_ma=findViewById(R.id.tv_ma);
        tv_ema=findViewById(R.id.tv_ema);
        tv_boll=findViewById(R.id.tv_boll);
        tv_vol=findViewById(R.id.tv_vol);
        tv_macd=findViewById(R.id.tv_macd);
        tv_kdj=findViewById(R.id.tv_kdj);
        tv_rsi=findViewById(R.id.tv_rsi);
        tv_roc=findViewById(R.id.tv_roc);
        tv_ma.setOnClickListener(this);
        tv_ema.setOnClickListener(this);
        tv_boll.setOnClickListener(this);
        tv_vol.setOnClickListener(this);
        tv_macd.setOnClickListener(this);
        tv_kdj.setOnClickListener(this);
        tv_rsi.setOnClickListener(this);
        tv_roc.setOnClickListener(this);

        initViewPort();
        tv_cangchi=findViewById(R.id.tv_cangchi);

       MsgView ll_tp=findViewById(R.id.ll_top);
        kline=findViewById(R.id.kline);
        kline.setMsgLL(ll_tp);
        kline.setOnClick(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(view==null)
                {
                    Intent intent = new Intent(act, KLineHengPingActivity.class);
                    intent.putExtra("id", id);
                    intent.putExtra("name", name);
                    intent.putExtra("index", klineType);
                    intent.putExtra("selectType", selectType);
                    act.startActivity(intent);
                }
                else
                {
                    nextZhiBiao();
                }

            }
        });







      TextView tv_name=(TextView) findViewById(R.id.tv_name);
      tv_name.setText(name);





     initTop(selectType);


    }
    private void initTop(int index)
    {
        TopView topv=findViewById(R.id.topv);
        topv.setSelectColor(getResources().getColor(R.color.color_text_style4));
        ArrayList<String> top=new ArrayList<>();
        top.add("分时");
        top.add("1分钟");
        top.add("5分钟");
        top.add("10分钟");
        top.add("30分钟");
        top.add("1小时");
        top.add("日k");
        TopView.onClickCall call=new TopView.onClickCall() {
            @Override
            public void back(int index) {


                kline.setType(index,zhibiaoTop);
                initKlneData(index);
               // Log.e("count",index+"");
            }
        };
        topv.setData(top,call,index);
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);

                colorTransitionPagerTitleView.setNormalColor(0xffa1adc8);
                colorTransitionPagerTitleView.setSelectedColor(0xff4385F3);
                colorTransitionPagerTitleView.setText(mTitleList[index]);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                        cindex=index;

                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
                indicator.setLineHeight(getResources().getDimension(R.dimen.value_3dp));
                indicator.setColors(0xff4385F3);
                return null;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
//        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
//            @Override
//            public Fragment getItem(int position) {
//                return mFragments.get(position);
//            }
//
//            @Override
//            public int getCount() {
//                return mFragments.size();
//            }
//        });
        mViewPager.setAdapter(new MyAdapter());
        mViewPager.setCurrentItem(cindex);
    }
    private void initKlneData(int index)
    {
        selectType=index;
        if(index==0)
        {

            klineType=0;
            initFenShiData();
            return;
        }
        else if(index==1)
        {
            klineType=1;

        }
        else if(index==2)
        {
            klineType=5;

        }
        else if(index==3)
        {
            klineType=10;

        }
        else if(index==4)
        {
            klineType=30;

        }
        else if(index==5)
        {
            klineType=60;

        }
        else if(index==6)
        {
            klineType=24;

        }

        KlneUtil ku=new KlneUtil();
        ku.getKline(this, id, klineType+"", new KlneUtil.IcbCall() {
            @Override
            public void comple(Object obj) {
                KLineHqResp resp=(KLineHqResp)obj;
                list=new ArrayList<>();
                StickData sd=null;
                String s1=null;
                for(int i=0;i<resp.getKlineinfoCount();i++)
                {
                    s1=resp.getKlineinfo(resp.getKlineinfoCount()-1-i).getStrkline();
                    if(s1!=null&&!s1.equals(""))
                    {
                        sd=MyDataParse.parse2(s1,klineType);
                        list.add(sd);
                    }


                }

                setKlineData();
            }
        });
    }
    private void initFenShiData()
    {
       showLoadingDialog();
        KlneUtil ku=new KlneUtil();
        ku.getFenshi(this, id, null, new KlneUtil.IcbCall() {
            @Override
            public void comple(Object obj) {
                KLineHqResp resp = (KLineHqResp)obj;
                if (resp.getKlineinfoCount() != 0) {
                    String s1 = resp.getKlineinfo(0).getStrkline();
                    fd=MyDataParse.parseFenShi(s1);
                    setFenShiData();
                }
            }
        });

    }
    private void setKlineData()
    {
        if(time!=null&&list!=null&&list.size()>0&&selectType!=0)
        {
            list.get(0).time_jiaoyo=time;
            kline.setData(list,klineType);
            if(list.size()>=2)
            {

                long min1= LineUtil.getMin(list.get(list.size()-2).getTime());
                long min2= LineUtil.getMin(list.get(list.size()-1).getTime());
                long start= LineUtil.countTime(time,list.get(list.size()-1).getTime(),klineType);
                long yu=(min2)%klineType;
//                if(min1==min2||(LineUtil.getMin(start) - min2) % klineType != 0)
//                {
//                    list.get(list.size()-1).setTime(start);
//                }
                if(min1==min2)
                {
                    list.get(list.size()-1).setTime(start);
                }
                else
                {
                    if((start-list.get(list.size()-1).getTime())% (klineType*60)!= 0)
                    {
                        list.get(list.size()-1).setTime(start);
                    }
                }

            }

            reZhibiao();
        }
    }
    private void setFenShiData()
    {
        if(time!=null&&fd!=null&&selectType==0)
        {


            fd.getParam().setDuration(time);
            count=NumberManager.getNumberDecimalDigits(scale);
            kline.setScalePrice(count);
            kline.setFenshiData(fd);
            //reZhibiao();
        }


    }

    /**
     * 初始化k线盘口数据
     */
    @Override
    protected void initData()
    {
//        String heyue=id+"|"+getDate();
//        Handler handler=new Handler()
//        {
//            @Override
//            public void handleMessage(Message msg) {
//                  if(msg.what==1)
//                  {
//                      MyDataParse mp=new MyDataParse();
//                      if(msg.obj!=null) {
//                          list = mp.parse(msg.obj.toString());
//                          if (list.size() > 1) {
//                              list.remove(list.size() - 1);
//                              kline.setData(list);
//
//                          }
//                      }
//                  }
//            }
//        };
//        RedisManager rm=new RedisManager(handler,heyue);
//        rm.start();

//        KlneUtil ku=new KlneUtil();
//        ku.getKline(this, id, "1", new KlneUtil.IcbCall() {
//            @Override
//            public void comple(Object obj) {
//                KLineHqResp resp=(KLineHqResp)obj;
//                list=new ArrayList<>();
//                StickData sd=null;
//                for(int i=0;i<resp.getKlineinfoCount();i++)
//                {
//                        sd=MyDataParse.parse2(resp.getKlineinfo(i).getStrkline());
//                        list.add(sd);
//                }
//                kline.setData(list);
//            }
//        });

//        ku.getFenshi(this,id, "", new KlneUtil.IcbCall() {
//            @Override
//            public void comple(Object obj) {
//                KLineHqResp resp=(KLineHqResp)obj;
//                Log.e("size",resp.getKlineinfoCount()+"");
//            }
//        });




    }


    /**
     * 得到当前场次
     * @return
     */
   public  String getCangChi()
   {
       String cdate="";
       String cangchi=null;

       Date  date=new Date();
       String formats   = "HH:mm";

       cdate = new SimpleDateFormat(formats, Locale.CHINA).format(new Date());

       if(time==null)
       {
         return "--";
       }
       ArrayList<String> times = new ArrayList<>();
       if (time.contains("|")) {
           String[] t1 = time.split("\\|");
           for (String s : t1) {
               times.add(s.split("-")[0]);
               times.add(s.split("-")[1]);
           }

       } else {
           times.add(time.split("-")[0]);
           times.add(time.split("-")[1]);
       }

       ArrayList<Integer> mins = new ArrayList<>();
       for(String minStr : times) {

           int min = Integer.parseInt(minStr.split(":")[0]) * 60 + Integer.parseInt(minStr.split(":")[1]);
           mins.add(min);
       }
       int cmin= Integer.parseInt(cdate.split(":")[0]) * 60 + Integer.parseInt(cdate.split(":")[1]);
       for(int i=0;i<mins.size();i=i+2)
       {
           int a=mins.get(i);
           int b=mins.get(i+1);
           if(cmin>=a&&cmin<=b)
           {
               cangchi=times.get(i)+"-"+times.get(i+1);
           }
       }
       return  cangchi;
   }
   private void showSelect(ArrayList<Market> list)
   {
       LinearLayout ll1=new LinearLayout(this);
       View  view1=null;
       LinearLayout ll=null;
        if(ll_select.getChildCount()==0)
        {

            view1 =  getLayoutInflater().inflate(R.layout.dialog_select_trade,ll1,false);
            ll_select.addView(view1);



        }
       ll=ll_select.findViewById(R.id.ll);
            TextView tv_name=null;
            GridView gv=null;
            ll.removeAllViews();
            ArrayList<Map<String,String>>  lists=null;
            for(int i=0;i<list.size();i++)
            {
                View   view= getLayoutInflater().inflate(R.layout.dialog_select_trade_item,ll1,false);
                tv_name=view.findViewById(R.id.tv_name);
                tv_name.setText(list.get(i).name);
                gv=view.findViewById(R.id.gv);

                String[] from={"text","id"};

                int[] to={R.id.tv_name,R.id.tv_id};
                lists=getData(list.get(i));

                SimpleAdapter adapter=new SimpleAdapter(this,lists,R.layout.dialog_select_trade_item2,from,to)

                {
                    @Override
                    public View getView(int position, View convertView, ViewGroup parent) {
                        View view=super.getView(position, convertView, parent);
                        TextView tv_name=view.findViewById(R.id.tv_name);

                        TextView tv_id=view.findViewById(R.id.tv_id);
                        String id2=tv_id.getText().toString();
                        if(id.equals(id2))
                        {
                            tv_name.setTextColor(0xffffffff);
                            tv_name.setBackgroundResource(R.drawable.bg_market_select2);
                        }
                        return view;
                    }
                };
                gv.setAdapter(adapter);
                ll.addView(view);
                gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                       TextView tv_name=view.findViewById(R.id.tv_name);
                        TextView tv_id=view.findViewById(R.id.tv_id);
                        name=tv_name.getText().toString();
                        id=tv_id.getText().toString();

                        //Log.e("name",name+":"+id);

                        reData();
                        ll_select.setVisibility(View.GONE);
                        iv_zhishi.setImageResource(R.drawable.klinegraph_icon_down);

                    }
                });
            }



       if(ll_select.getVisibility()==View.VISIBLE)
       {
            ll_select.setVisibility(View.GONE);
            iv_zhishi.setImageResource(R.drawable.klinegraph_icon_down);
       }
       else
       {
           ll_select.setVisibility(View.VISIBLE);
           iv_zhishi.setImageResource(R.drawable.klinegraph_icon_up);
       }
   }
    private  ArrayList<Map<String,String>> getData(Market market)
    {
        ArrayList<Map<String,String>>  lists=new ArrayList<>();
        Map<String,String> map=null;
        for(int i=0;i<market.treadys.size();i++)
        {
            map=new HashMap<>();
            map.put("text",market.treadys.get(i));
            map.put("id",market.treadys_id.get(i));
            lists.add(map);
        }

        return  lists;
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent=new Intent();

       // fenshiView.setDataAndInvalidate(data);
        switch (v.getId()) {
            case R.id.iv_search:
                GoodsSelectDialog gsd=new GoodsSelectDialog(this);
                gsd.showDialog();
                break;
            case R.id.iv_close:
                finish();
                break;
            case R.id.tv_add:
                if(DBMarketS.isHas(id)) {
                    mDBManager.deleteMarketS(id);
                    tv_add.setText("加自选");
                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH,
                            new EventZixuanData(new MyContractBean(id, name), false)));
                } else {
                    DBMarketS ms=new DBMarketS();
                    ms.setId(id);
                    ms.setName(name);
                    mDBManager.setMarketS(ms);
                    tv_add.setText("删自选");
                    EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH,
                            new EventZixuanData(new MyContractBean(id, name), true)));
                }
                break;
            case R.id.tv_xiadan:
                if(!mDBManager.isLogined())
                {

                    intent.setClass(this, LoginActivity.class).putExtra("tag", 1);
                    startActivity(intent);
                    return;
                }
                if(mDBManager.getUser() != null &&
                        mDBManager.getUser().getRiskAuthState() == 0 &&
                        mDBManager.getIsOldUser() == 0) {
                    new RiskInvestigationDialog(this, new RiskInvestigationDialog.OnClickListener() {
                        @Override
                        public void onWriteClick() {
                            startActivity(new Intent(KLineActivity.this, RiskStateActivity.class)
                                    .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                        }

                        @Override
                        public void onCloseClick() {
                        }
                    }).show();
                    return;
                }

                pm=new PlaceOrderDialogManager(this);
                pm.showDialog2();
                if(buy!=null&&buy.size()>0)
                {
                    pm.setData(id,name,tv_price.getText().toString());
                }
                else
                {
                    pm.setData(id,name,null);
                }
                break;



            case R.id.ll_left:
                finish();
                 break;
            case R.id.tv_zhixuan:
                        if(DBMarketS.isHas(id)) {
                            mDBManager.deleteMarketS(id);
                            tv_zhixuan.setText("加自选");
                            EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH,
                                    new EventZixuanData(new MyContractBean(id, name), false)));
                        } else {
                            DBMarketS ms=new DBMarketS();
                            ms.setId(id);
                            ms.setName(name);
                            mDBManager.setMarketS(ms);
                            tv_zhixuan.setText("删自选");
                            EventBusUtils.post(new EventMessage<>(EventCode.EVENT_ZIXUAN_REFRESH,
                                    new EventZixuanData(new MyContractBean(id, name), true)));
                        }
                break;
            case R.id.ll_name:

                ArrayList<Market> list=SwitchData(MarketFragment.getRespMarket());

                showSelect(list);
                break;
            case R.id.tv_buy:
                if(!mDBManager.isLogined())
                {

                    intent.setClass(this, LoginActivity.class).putExtra("tag", 1);
                    startActivity(intent);
                    return;
                }
                if(mDBManager.getUser() != null &&
                        mDBManager.getUser().getRiskAuthState() == 0 &&
                        mDBManager.getIsOldUser() == 0) {
                    new RiskInvestigationDialog(this, new RiskInvestigationDialog.OnClickListener() {
                        @Override
                        public void onWriteClick() {
                            startActivity(new Intent(KLineActivity.this, RiskStateActivity.class)
                                    .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                        }

                        @Override
                        public void onCloseClick() {
                        }
                    }).show();
                    return;
                }
                if(pm!=null&&pm.isShow())
                {
                    return;
                }
                pm=new PlaceOrderDialogManager(this);
                pm.showDialog();
                   if (buy != null && buy.size() > 0) {
                       pm.setData(id, name, tv_price.getText().toString());
                   } else {
                       pm.setData(id, name, null);
                   }



                break;
            case R.id.tv_sell:
                if(!mDBManager.isLogined())
                {

                    intent.setClass(this, LoginActivity.class).putExtra("tag", 1);
                    startActivity(intent);
                    return;
                }
                if(mDBManager.getUser() != null &&
                        mDBManager.getUser().getRiskAuthState() == 0 &&
                        mDBManager.getIsOldUser() == 0) {
                    new RiskInvestigationDialog(this, new RiskInvestigationDialog.OnClickListener() {
                        @Override
                        public void onWriteClick() {
                            startActivity(new Intent(KLineActivity.this, RiskStateActivity.class)
                                    .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                        }

                        @Override
                        public void onCloseClick() {
                        }
                    }).show();
                    return;
                }
               intent.setClass(this,TradeDocumentaryActivity.class);
               startActivity(intent);
                finish();
                break;


            case R.id.iv_chicang:
                startActivity(new Intent(this, MainActivity.class)
                        .putExtra("item", 1));
                finish();
                break;
            case R.id.iv_zhixuan:
                intent.setClass(act,ZixuanActivity.class);
                startActivity(intent);
                finish();

                break;
            case R.id.iv_hangqing:
                startActivity(new Intent(this, MainActivity.class)
                        .putExtra("item", 0));
                finish();
                break;
            default:
                break;
        }
    }






    private ArrayList<Market> SwitchData(RespMarket respMarket)
    {
        ArrayList<Market> list=new ArrayList<>();
        if(respMarket==null)
        {
            return list;
        }
        Market mk=null;

        ArrayList<MarketBean> marketList=respMarket.getMarketList();
        ArrayList<ContractBean> contractList=respMarket.getContractList();
        for(int i=0;i<marketList.size();i++)
        {
            mk=new Market();
               mk.name=marketList.get(i).marketName;
               for(int a=0;a<contractList.size();a++)
               {
                   if(marketList.get(i).id.equals(contractList.get(a).marketId))
                   {
                       mk.treadys.add(contractList.get(a).contractName);
                       mk.treadys_id.add(contractList.get(a).contractNo);
                   }
               }
               if(mk.treadys.size()>0) {
                   list.add(mk);
               }
        }
        return list;

    }

    /**
     * 获取交易时间
     */
    private void getTradeTime()
{
    ReqGetTradeTime rm=new ReqGetTradeTime();
    VolleyRequestUtils.getInstance().sendRequest(this.toString(), rm, new INetWorkCallback() {
        @Override
        public void onSuccess(Object response) {
            mRespTradeTime=(RespTradeTime)response;

            String goodsid=MarketFragment.getRespMarket().goodsId(id);
            if(goodsid==null||"".equals(goodsid))
            {
                return;
            }

//            GoodsFragment goodsf=(GoodsFragment) mFragments.get(1);
//            goodsf.setTime(mRespTradeTime.getTime(goodsid));
            time=mRespTradeTime.getTime(goodsid);
           setFenShiData();
            String s1=getCangChi();
            if(s1!=null)
            {
                tv_cangchi.setText("场次"+getCangChi());
            }
            else
            {
                tv_cangchi.setText("不在交易时间段");
            }

        }

        @Override
        public void onFail(BaseResponse baseResponse) {

        }
    });
}



    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }
   private void setData(MyContractBean mb)
   {
       int orientation = getResources().getConfiguration().orientation;
       if (orientation == Configuration.ORIENTATION_LANDSCAPE)
       {


       } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {

           GearFragment gf=(GearFragment) mFragments.get(0);
           if(mb!=null)
           {
               gf.setData(mb);
               setTop(mb,null);
               kline.setTop(mb);
           }
       }

   }

    private long tickTime;
    MyContractBean mb;

    @Override
    public void onReceiveEvent(EventMessage event) {
        super.onReceiveEvent(event);
        switch (event.getCode()){
            case EventCode.EVENT_MARKET:
                try {
                    if(!isForeground(act,act.getClass().getName()))
                    {
                        return;
                    }
                    HqMsg.YsHqInfo yh = (HqMsg.YsHqInfo) event.getData();
                    String s1=yh.getCommodityNo()+yh.getContractNo1();
                    if(!id.equals(s1))
                    {
                        return;
                    }
                    yhc=yh;

                    //Log.e("成交量", yhc.getTAPIDTSTAMP() +"|" + yhc.getQLastQty());
                    // GearFragment gf=(GearFragment) mFragments.get(0);
                    // gf.setData(yh);

                    long t = TimeUtil.Date2TimeStamp2(yh.getTAPIDTSTAMP(), null);
                    if (t == tickTime && yh.getQLastQty() == 0) {
                        return;
                    }
                    tickTime = t;

                    mb = MyContractBean.switchData(yhc, count);
                    //Log.e("test1",mb.time_test+": "+mb.last+"");
//                    Log.e("test1",yhc.getTAPIDTSTAMP() + "------" + yhc.getQLastQty());
//                            + " 1:" + yhc.getQBidQty(0) + " 2:" + yhc.getQBidQty(1) + " 3:" + yhc.getQBidQty(2)
//                            + " 4:" + yhc.getQBidQty(3) + " 5:" + yhc.getQBidQty(4)
//                            + " 1:" + yhc.getQBidPrice(0) + " 2:" + yhc.getQBidPrice(1) + " 3:" + yhc.getQBidPrice(2)
//                            + " 4:" + yhc.getQBidPrice(3) + " 5:" + yhc.getQBidPrice(4)
//                            + " 1:" + yhc.getQAskQty(0) + " 2:" + yhc.getQAskQty(1) + " 3:" + yhc.getQAskQty(2)
//                            + " 4:" + yhc.getQAskQty(3) + " 5:" + yhc.getQAskQty(4)
//                            + " 1:" + yhc.getQAskPrice(0) + " 2:" + yhc.getQAskPrice(1) + " 3:" + yhc.getQAskPrice(2)
//                            + " 4:" + yhc.getQAskPrice(3) + " 5:" + yhc.getQAskPrice(4));
                    //Log.e("test1",yhc.getTAPIDTSTAMP() + "------" + yhc.getQLastQty());
                    setData(mb);

                    if( klineType!=0) {
                        upDateKline(mb);
                    }


                 if(klineType==0) {
                    updateFenshi(mb);

                     buy = new ArrayList<>();
                     ArrayList<GearBean> sell = new ArrayList<>();


                     GearBean gb = null;
                     for (int i = 0; i < 5; i++) {
                         gb = new GearBean();
                         gb.id = 1 + i + "";
                         gb.price = NumberManager.getString4or5(yh.getQBidPrice(i) + "", "1", count);
                         gb.num = yh.getQBidQty(i) + "";

                         buy.add(gb);

                         gb = new GearBean();
                         gb.id = 1 + i + "";

                         gb.price = NumberManager.getString4or5(yh.getQAskPrice(i) + "", "1", count);
                         gb.num = yh.getQAskQty(i) + "";
                         sell.add(gb);
                     }

                     if (buy.size() > 1 && pm != null) {
                         pm.setPrice(tv_price.getText().toString());
                     }
                     kline.setLastPrice(mb.ClosingPrice);
                     kline.setGearData(buy, sell);
                 }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                break;
            case EventCode.EVENT_MESSAGE_NETWORK:
                reData();
                break;
            case EventCode.EVENT_LOGIN_TIPS:
                if (mDBManager.getIsOldUser() == 1) {
                    new CustomDialog(this, new CustomDialog.OnClickListener() {
                        @Override
                        public void onLeftClick() {
                        }

                        @Override
                        public void onRightClick() {
                            startActivity(new Intent(KLineActivity.this, UpdateRegisterAgreementActivity.class)
                                    .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                        }
                    }).setContent("尊敬的客户，为了给您提供更完善的交易服务，请您完善账户资料补充申请（通讯地址、资产职业信息），感谢您的配合！")
                            .setLeft("稍后").setRight("进入").setGravity(Gravity.LEFT).show();
                } else if (mDBManager.getUser().getRiskAuthState() == 0) {
                    new RiskInvestigationDialog(this, new RiskInvestigationDialog.OnClickListener() {
                        @Override
                        public void onWriteClick() {
                            startActivity(new Intent(KLineActivity.this, RiskStateActivity.class)
                                    .putExtra("mobile", mDBManager.getUser().getMobileNo()));
                        }

                        @Override
                        public void onCloseClick() {
                        }
                    }).show();
                }
                break;
                default:
                    break;
        }
    }

    /**
     * 跟新分时数据
     */
   private void updateFenshi(MyContractBean mb)
   {
       if(klineType!=0)
       {
           return;
       }
       if(fd==null||fd.getData()==null||fd.getData().size()==0)
       {
           return;
       }
       CMinute last=fd.getData().get(fd.getData().size()-1);
//       if(NumberManager.isDaYu(last.price+"",mb.last)==0)
//       {
//           return;
//       }
       CMinute cm=new CMinute();
       if(!mb.last.equals(""))
       {
           cm.setPrice(Double.parseDouble(mb.last));
       }

       // String val= NumberUtil2.getSubString(mb.TotalNum,fd.getTotalVal(),0);
       if(mb.vol<0)
       {
           mb.vol=0;
       }
       cm.setCount(mb.vol);
       cm.setChange(mb.change);
       cm.setChg(mb.chg);
       cm.setRate(Double.parseDouble(mb.chg.substring(0,mb.chg.indexOf("%"))));
       cm.setTime(mb.time);
       cm.setAverage(mb.Average);
       //fd.addData(cm);
       //setFenShiData();

       kline.updateFenshiData(cm);

   }

  private void upDateKline(MyContractBean mb)
  {
      if(mb.vol<1)
      {
          return;
      }
      StickData sd=new StickData();
      sd.setClose(Double.parseDouble(mb.last));

      sd.setHigh(Float.parseFloat(mb.last));
      //sd.setLast(Double.parseDouble(mb.last));
      sd.setLow(Double.parseDouble(mb.last));


      sd.setOpen(Double.parseDouble(mb.last));


      sd.setCount_total(Double.parseDouble(mb.TotalNum));
      sd.setCount(mb.vol);
      sd.setTime(mb.time);
      sd.test_time=mb.time_test;
      kline.updateKlineData(sd);
  }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void qingcang()
    {
        int positionId=pi.getlPositionNo().intValue();
        pm = new PlaceOrderDialogManager(this);
        pm.showDialog();
        pm.setData(id, name, null);

        pm.setChiCangId(positionId);
        if(pi.getcPositionFlag().equals("1"))
        {
            pm.setPingCang(1);
        }else if(pi.getcPositionFlag().equals("2"))
        {
            pm.setPingCang(2);
        }
        else
        {
            pm.setPingCang(0);
        }
        pm.setNum(pi.getlCurrentAmount() - pi.getlPresaleAmount()+"");
    }

    private void setTop(MyContractBean mb,String name)
    {


          if(mb!=null) {
              tv_price.setText(mb.last);
              tv_change.setText(mb.change);
              tv_chg.setText(mb.chg);
              if(NumberManager.isDaYu(mb.change,"0")>0)
              {
                  tv_price.setTextColor(MResUtil.getUpColor());
                  tv_change.setTextColor(MResUtil.getUpColor());
                  tv_chg.setTextColor(MResUtil.getUpColor());
                  if(mb.change.contains("+"))
                  {
                      tv_change.setText(mb.change);
                  }
                  else
                  {
                      tv_change.setText("+"+mb.change);
                  }
                  if(mb.chg.contains("+"))
                  {
                      tv_chg.setText(mb.chg);
                  }
                  else
                  {
                      tv_chg.setText("+"+mb.chg);
                  }
              }
              else if(NumberManager.isDaYu(mb.change,"0")==0)
              {
                  tv_price.setTextColor(MResUtil.getPingColor());
                  tv_change.setTextColor(MResUtil.getPingColor());
                  tv_chg.setTextColor(MResUtil.getPingColor());
              }
              else
              {
                  tv_price.setTextColor(MResUtil.getDownColor());
                  tv_change.setTextColor(MResUtil.getDownColor());
                  tv_chg.setTextColor(MResUtil.getDownColor());

                  if(mb.change.contains("-"))
                  {
                      tv_change.setText(mb.change);
                  }
                  else
                  {
                      tv_change.setText("-"+mb.change);
                  }
                  if(mb.chg.contains("-"))
                  {
                      tv_chg.setText(mb.chg);
                  }
                  else
                  {
                      tv_chg.setText("-"+mb.chg);
                  }
              }
          }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //instance.start(this);


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initView();
        initTop(selectType);
        reZhibiao();
        if(selectType==0)
        {
            initFenShiData();
        }
        else
        {
            initKlneData(selectType);
        }
        int orientation = getResources().getConfiguration().orientation;
        if (orientation != Configuration.ORIENTATION_PORTRAIT)
        {

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        //instance.stop();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
//        int orientation = getResources().getConfiguration().orientation;
//        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            setContentView(R.layout.activity_klinehengping);
//        } else if (orientation == Configuration.ORIENTATION_PORTRAIT) {
//            setContentView(R.layout.activity_kline);
//        }

//      if(newConfig.orientation== Configuration.ORIENTATION_LANDSCAPE)
//      {
//          Intent intent=new Intent(act, KLineHengPingActivity.class);
//          intent.putExtra("id",id);
//          intent.putExtra("name",name);
//          intent.putExtra("index",klineType);
//          act.startActivity(intent);
//      }


    }


    public class MyAdapter extends PagerAdapter
    {

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView(mFragments.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            //viewpger 两个页面循环滑动会出现崩溃问题 下面是解决方案

            container.addView(mFragments.get(position));
            return mFragments.get(position);
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return  arg0==arg1;
        }

        @Override
        public int getItemPosition(Object object) {
            // TODO Auto-generated method stub
            return POSITION_NONE;
        }
    }


}
